import 'package:flutter/widgets.dart';
import 'package:library_base/entities/goods_child_entity.dart';
import 'package:library_base/entities/goods_child_info_entity.dart';
import 'package:library_base/entities/shipper_entity.dart';
import 'package:library_base/entities/suppliers_entity.dart';
import 'package:library_base/entities/suppliers_shops_list_entity.dart';
import 'package:library_base/entities/task_detail_entity.dart';
import 'package:library_base/entities/warehouse_entity.dart';
import 'package:library_base/net/apis.dart';
import 'package:library_base/network/http_config.dart';
import 'package:library_base/provider/base_controller.dart';
import 'package:get/get.dart';
import 'package:library_base/route/routers.dart';
import 'package:library_base/utils/num_util.dart';
import 'package:library_base/utils/toast_util.dart';
import 'package:library_base/widget/dialog/dialog_util.dart';

class CreatePurchaseOrderController extends BaseController {
  var isEdit = false;

  Rxn<SuppliersEntity?> supplier = Rxn<SuppliersEntity?>();

  Rxn<WarehouseEntity?> warehouse = Rxn<WarehouseEntity?>();

  Rxn<ShipperEntity?> consignor = Rxn<ShipperEntity?>();

  ///已选中的供应商下的其中一个门店
  SuppliersShopsListEntity? suppliersShopsListEntity;

  TextEditingController remarkTextEditingController = TextEditingController();

  FocusNode remarkFocusNode = FocusNode();

  Rxn<TaskDetailEntity?> taskDetailEntity = Rxn<TaskDetailEntity?>();

  ///已选中供应商商店
  SuppliersShopsListEntity? shop;

  var purchaseOrderNo = '-'.obs;

  String id = '';

  ///商品数量
  var numberOfProducts = 0.0.obs;

  ///采购单金额
  var purchaseOrderAmount = 0.00.obs;

  ///是否显示提交草稿按钮
  bool isShowSubmitDraft = true;

  ///是否需要生成销售单
  bool isShowGenerateSalesOrderDialog = true;

  /// 实体类
  RxList<GoodsChildEntity> listDataSelected = <GoodsChildEntity>[].obs;

  @override
  void onCreate() {
    var map = getArguments();
    if (map != null) {
      taskDetailEntity.value = (map as Map<String, dynamic>)['TaskDetailEntity'];
      shop =  taskDetailEntity.value!.shop;
      isShowSubmitDraft = map['isShowSubmitDraft']??true;
      isShowGenerateSalesOrderDialog = map['isShowGenerateSalesOrderDialog']??true;
      isEdit = true;
      if (taskDetailEntity.value != null) {
        purchaseOrderNo.value = taskDetailEntity.value!.purchaseOrderNumber;
        id = taskDetailEntity.value!.id;
        remarkTextEditingController.text = taskDetailEntity.value!.remark;
        //--------------
        if (taskDetailEntity.value!.supplierId != null) {
          supplier.value = SuppliersEntity();
          supplier.value!.id = taskDetailEntity.value!.supplierId!;
          supplier.value!.name = taskDetailEntity.value!.supplierName;
          supplier.value!.isSelect = true;
        }
        //--------------
        if (taskDetailEntity.value!.warehouseId != null) {
          warehouse.value = WarehouseEntity();
          warehouse.value!.id = taskDetailEntity.value!.warehouseId!;
          warehouse.value!.whName = taskDetailEntity.value!.warehouseName;
          warehouse.value!.isSelect = true;
        }
        //--------------
        consignor.value = ShipperEntity();
        consignor.value!.id = taskDetailEntity.value!.shipperId;
        consignor.value!.shipperName = taskDetailEntity.value!.shipperName;
        consignor.value!.isSelect = true;

        //--------------

        for (var element in taskDetailEntity.value!.details) {
          GoodsChildEntity goodsChildEntity = GoodsChildEntity();
          goodsChildEntity.goodsName = element.goodsName;
          goodsChildEntity.goodsCode = element.goodsCode;
          goodsChildEntity.unit = element.unit;
          goodsChildEntity.price = element.price;
          goodsChildEntity.totalWeight = element.totalWeight;
          goodsChildEntity.serviceCost = element.serviceCost;
          goodsChildEntity.totalCount = element.goodsCount;
          goodsChildEntity.standardWeight = element.standardWeight;
          goodsChildEntity.singleEntry = element.singleEntry;

          numberOfProducts.value = NumUtil.add(numberOfProducts.value, element.goodsCount);
          purchaseOrderAmount.value =
              NumUtil.add(purchaseOrderAmount.value, goodsChildEntity.purchaseAmount!);
          purchaseOrderAmount.value = NumUtil.add(purchaseOrderAmount.value, element.serviceCost);

          List<GoodsChildInfoEntity> goodsDetails = [];
          for (var goodsDetail in element.goodsDetails) {
            GoodsChildInfoEntity goodsChildInfoEntity = GoodsChildInfoEntity();
            goodsChildInfoEntity.goodsPurchaseCode = goodsDetail.goodsPurchaseCode;
            goodsChildInfoEntity.weight = goodsDetail.weight;
            goodsChildInfoEntity.serviceCost = goodsDetail.serviceCost;
            goodsDetails.add(goodsChildInfoEntity);
          }
          goodsChildEntity.goodsDetails = goodsDetails;
          listDataSelected.value.add(goodsChildEntity);
        }
        listDataSelected.value;
      }
    }
  }

  updateCount() {
    numberOfProducts.value = 0.0;
    purchaseOrderAmount.value = 0.0;
    for (var element in listDataSelected.value) {
      numberOfProducts.value = NumUtil.add(numberOfProducts.value, element.totalCount ?? 0.0);
      purchaseOrderAmount.value =
          NumUtil.add(purchaseOrderAmount.value, element.purchaseAmount ?? 0.0);
      purchaseOrderAmount.value =
          NumUtil.add(purchaseOrderAmount.value, element.serviceCost ?? 0.0);
    }
  }

  saveAndSubmit({bool isEmpty = false}) {
    Map<String, dynamic> params = {};

    if (purchaseOrderNo.value != '-') {
      params['id'] = id;
    }
    params['supplierId'] = supplier.value!.id;
    params['warehouseId'] = warehouse.value!.id;
    params['shipperId'] = consignor.value!.id;
    params['remark'] = remarkTextEditingController.text;

    if(suppliersShopsListEntity!=null){
      params['generateOrder'] = true;
      params['supplierShopId'] = suppliersShopsListEntity!.id;
    }

    List<Map<String, dynamic>> detailsList = [];
    for (var element in listDataSelected.value) {

      Map<String, dynamic> detailsMap = {};
      detailsMap['goodsCode'] = element.goodsCode;
      detailsMap['totalCount'] = element.totalCount;
      detailsMap['price'] = element.price;
      detailsMap['totalWeight'] = element.totalWeight;
      detailsMap['serviceCost'] = element.serviceCost;

      List<Map<String, dynamic>> goodsDetailsList = [];
      for (var detail in element.goodsDetails) {
        Map<String, dynamic> goodsDetail = {};
        goodsDetail['goodsPurchaseCode'] = detail.goodsPurchaseCode;
        goodsDetail['weight'] = detail.weight;
        goodsDetail['serviceCost'] = detail.serviceCost;

        goodsDetailsList.add(goodsDetail);
      }

      detailsMap['goodsDetails'] = goodsDetailsList;

      detailsList.add(detailsMap);

      params['details'] = detailsList;
    }
    requestUniversal<bool>(Apis.FINISHED,
        method: FBResultFul.PUT,
        params: params,
        isShowToastTip: true,
        tipSuccess: '提交成功', resultSuccessCall: (success) async {
      if(isEdit){
        if(isShowGenerateSalesOrderDialog){
          Get.until((route) => Get.currentRoute == Routers.workbench);
        }else{
          Get.until((route) => Get.currentRoute == Routers.workbench);
        }
      }else{
        Get.until((route) => Get.currentRoute == Routers.workbench);
      }
    });
  }

  ///保存草稿
  saveDraft() {
    Map<String, dynamic> params = {};
    if (purchaseOrderNo.value != '-') {
      params['id'] = id;
    }
    params['supplierId'] = supplier.value!.id;
    params['warehouseId'] = warehouse.value!.id;
    params['shipperId'] = consignor.value!.id;
    params['remark'] = remarkTextEditingController.text;

    List<Map<String, dynamic>> detailsList = [];

    for (var element in listDataSelected.value) {
      Map<String, dynamic> detailsMap = {};
      detailsMap['goodsCode'] = element.goodsCode;
      detailsMap['totalCount'] = element.totalCount;
      detailsMap['price'] = element.price;
      detailsMap['totalWeight'] = element.totalWeight;
      detailsMap['serviceCost'] = element.serviceCost;

      List<Map<String, dynamic>> goodsDetailsList = [];
      for (var detail in element.goodsDetails) {
        Map<String, dynamic> goodsDetail = {};
        goodsDetail['goodsPurchaseCode'] = detail.goodsPurchaseCode;
        goodsDetail['weight'] = detail.weight;
        goodsDetail['serviceCost'] = detail.serviceCost;
        goodsDetailsList.add(goodsDetail);
      }

      detailsMap['goodsDetails'] = goodsDetailsList;

      detailsList.add(detailsMap);

      params['details'] = detailsList;
    }
    requestUniversal<bool>(Apis.TASKS_DETAIL,
        method: FBResultFul.POST,
        params: params,
        tipSuccess: '保存草稿成功',
        isShowToastTip: true, resultSuccessCall: (success) async {
      Get.back();
      Get.back();
    });
  }

  generateSalesOrder(){
    if(supplier.value == null){
      ToastUtil.normal("请先选择供应商");
      return;
    }
    requestUniversal<SuppliersShopsListEntity>(Apis.SUPPLIERS_SHOPS_LIST,
        method: FBResultFul.GET,
        queryParameters: {
          "supplierId":supplier.value!.id,
        },
        resultSuccessListCall: (data) async {
          if(data.isEmpty){
            ToastUtil.normal("该供应商暂无门店,不可生成销售单");
            return;
          }
          var map = {};
          map["SuppliersShopsListEntity"] = data;
          DialogUtil.showGenerateSalesOrderDialog(arguments: map);
        });
  }

  bool isCanShowBottomOption() {
    if (supplier.value == null) {
      ToastUtil.waring('请选择供货商');
      return false;
    }

    if (warehouse.value == null) {
      ToastUtil.waring('请选择收货仓');
      return false;
    }

    if (consignor.value == null) {
      ToastUtil.waring('请选择货主');
      return false;
    }

    if (listDataSelected.value.isEmpty) {
      ToastUtil.waring('请选择商品');
      return false;
    }

    for (var element in listDataSelected.value) {
      if (element.totalCount == null) {
        ToastUtil.waring('还有商品未录入信息');
        return false;
      }
    }
    return true;
  }
}
